package com.kzw.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;

@MultipartConfig
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setCharacterEncoding("UTF-8");
		String name = req.getParameter("name");
		System.out.println(name);
		
		Part part = req.getPart("myfile");
		if(part != null) {
			String val = part.getHeader("content-disposition");
			String fname = val.replaceFirst(".*filename=\"(.*?)\".*", "$1");
			InputStream is = part.getInputStream();
			
			String upload = req.getServletContext().getRealPath("/upload");
			OutputStream os = new FileOutputStream(new File(upload, fname));
			
			IOUtils.copy(is, os);
			is.close();
			os.close();
		}
		
		
	}
	
}
